/*
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package net.javlov.vf;

import java.util.HashMap;
import java.util.Iterator;

import net.javlov.State;

/**
 * Value table using traces. Wraps around a regular value table. Traces are created or
 * updated *only* when calling {@link #update(State, double)}, not when calling any of
 * the {@code set} methods.
 * 
 * @author Matthijs Snel
 *
 */
public class TracedValueTable<T> implements ValueTable<T> {

	private static final long serialVersionUID = -733141599750754061L;

	protected ValueTable<T> table;
	
	protected HashMap<State<? extends T>, StateTrace> traceTable;
	
	protected StateTrace traceTemplate;
	
	protected double threshold;
	
	public TracedValueTable(ValueTable<T> vtable, StateTrace traceTemplate, double threshold) {
		table = vtable;
		traceTable = new HashMap<State<? extends T>, StateTrace>(30);
		this.traceTemplate = traceTemplate;
		this.threshold = threshold;
	}
	
	@Override
	public Value get(State<? extends T> s) {
		return table.get(s);
	}

	@Override
	public void set(State<? extends T> s, Value val) {
		table.set(s, val);		
	}

	@Override
	public void setInitializer(ValueFunction<T> vf) {
		table.setInitializer(vf);		
	}

	@Override
	public double getValue(State<? extends T> s) {
		return table.getValue(s);
	}

	@Override
	public void init() {
		table.init();
		traceTable.clear();
	}
	
	@Override
	public void reset() {
		table.reset();
		traceTable.clear();
	}
	
	@Override
	public Double queryValue(State<? extends T> s) {
		return table.queryValue(s);
	}

	@Override
	public void setValue(State<? extends T> s, double value) {
		table.setValue(s, value);		
	}

	@Override
	public int size() {
		return table.size();
	}
	
	@Override
	public void update(State<? extends T> s, double delta) {
		StateTrace trace = traceTable.get(s);
		if ( trace == null ) {
			trace = traceTemplate.newInstance();
			Value val = table.get(s);
			trace.firstVisit(s, val);
			traceTable.put(s, trace);
		} else {
			trace.visit();
		}
		updateAll(s, delta);
	}
	
	protected void updateAll(State<? extends T> s, double delta) {
		Iterator<StateTrace> itr = traceTable.values().iterator();
		StateTrace tr;
		while ( itr.hasNext() ) {
			tr = itr.next();
			tr.getValue().add( tr.getTrace()*delta );
			tr.update(s);
			if ( tr.getTrace() < threshold )
				itr.remove();
		}
	}

}
